import React, { useState, useRef, useEffect } from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  SafeAreaView,
  TouchableOpacity,
  Appearance,
} from 'react-native';
import SearchNoteCardItemList from '../Components/SearchNoteCardItemList.tsx'; // 确保路径正确
import Icon from 'react-native-vector-icons/FontAwesome';

// @ts-ignore
const SearchScreen = ({navigation}) => {
  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText, setDebouncedSearchText] = useState('');
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const [colorScheme, setColorScheme] = useState(Appearance.getColorScheme());

  useEffect(() => {
    const subscription = Appearance.addChangeListener(({ colorScheme }) => {
      setColorScheme(colorScheme);
    });

    return () => subscription.remove();
  }, []);

  // 清除input
  const handleClearInput = () => {
    setSearchText('');
    setDebouncedSearchText('');
  };

  // 设置1s的防抖，在input变化后1s再修改content,防止useEffect调用过快
  const handleInputChange = (text: string) => {
    setSearchText(text);
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = setTimeout(() => {
      setDebouncedSearchText(text);
    }, 1000);
  };

  const isDarkMode = colorScheme === 'dark';

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: isDarkMode ? '#121212' : '#f5f5f5' }]}>
      <View style={styles.searchContainer}>
        <TextInput
          style={[styles.input, { backgroundColor: isDarkMode ? '#242424' : '#fff', color: isDarkMode ? '#fff' : '#000' }]}
          placeholder="请输入搜索内容"
          placeholderTextColor={isDarkMode ? '#888' : '#888'}
          value={searchText}
          onChangeText={handleInputChange}
        />
        {searchText.length > 0 && (
          <TouchableOpacity style={styles.clearButton} onPress={handleClearInput}>
            <Icon name="times" size={20} color={isDarkMode ? '#fff' : '#000'} />
          </TouchableOpacity>
        )}
      </View>
      <SearchNoteCardItemList
        author=""
        content={debouncedSearchText}
        navigation={navigation}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 20,
    position: 'relative',
  },
  input: {
    flex: 1,
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginRight: 10,
    paddingLeft: 10,
    borderRadius: 20,
  },
  clearButton: {
    position: 'absolute',
    right: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default SearchScreen;
